package com.doeis.minaserver.module;

import org.apache.log4j.Logger;

import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.container.BasicModule;
import com.doeis.minaserver.packet.InfoPacket;
import com.doeis.minaserver.session.ClientConnection;

public class InfoPacketRouter extends BasicModule {
	private static final Logger log = Logger.getLogger(InfoPacketRouter.class);
		
	private UserManager userManager;
	
	public InfoPacketRouter() {
		super("InfoPacket Router");
	}

	@Override
	public void initialize(NettyServer server) {
		this.server = server;		
	}
	
	@Override
	public void start(){
		userManager = server.getUserManager();
	}
	
	public void route(ClientConnection fromConn,InfoPacket packet){
	
		switch ( packet.getCmd() ) {
		case InfoPacket.CMD_HEART_BEAT:
//			log.debug(fromConn.getUserid()+"发送心跳了");
			break;
		case InfoPacket.CMD_SHUTDOWN_SERVER:
			shutDownServer(fromConn,packet);
			break;
		//用户登陆
		case InfoPacket.CMD_USER_LOGIN:
			doUserLogin(fromConn,packet);
			break;
			
		//用户推送信息
		case InfoPacket.CMD_BAI_PUSH:
			baiduPush(fromConn,packet);
			break;
		
		default:
			break;
		}		
	}

	/**
	 * 网络登陆过程中
	 */
	private void doUserLogin(ClientConnection clientConn,InfoPacket p){	
		userManager.loginAction(clientConn, p);
	}
	
	/**
	 * 网络登陆过程中
	 */
	private void baiduPush(ClientConnection clientConn,InfoPacket p){	
		userManager.baiduPush(clientConn, p);
	}
	
	/**
	 * 关闭服务器
	 * @param clientConn
	 * @param p
	 */
	private void shutDownServer(ClientConnection clientConn,InfoPacket p){
		
		String remoteAddress = clientConn.getHostAddress().toString();
		
		//只有本机才能关闭服务器
		if(remoteAddress.equalsIgnoreCase("localhost") || remoteAddress.equalsIgnoreCase("127.0.0.1")){
			server.stop();
		}else{
			log.warn("服务器关闭失败。ip="+remoteAddress);
		}

	}
	
}
